const express = require('express');
const router = express.Router();
const { getUserByUsername, createUser } = require('../dataBase/api');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');

// JWT 密钥
const JWT_SECRET = 'your-secret-key';

// 登录路由
router.post('/signin', async (req, res) => {
  try {
    const { username, password } = req.body;

    // 查找用户
    const user = await getUserByUsername(username);
    console.log(user[0],123123123);
    
    if (!user) {
      return res.status(401).json({ message: '用户名或密码错误' });
    }

    // 验证密码
    const isValidPassword = await bcrypt.compare(password, user[0].password);
    console.log(isValidPassword,33333);
    
    if (!isValidPassword) {
      return res.status(401).json({ message: '用户名或密码错误' });
    }

    // 生成 JWT token
    const token = jwt.sign(
      { userId: user.id, username: user.username },
      JWT_SECRET,
      { expiresIn: '24h' }
    );

    // 返回用户信息和 token
    res.json({
      code: 200,
      message: '登录成功',
      data: {
        token,
        user: {
          id: user.id,
          username: user.username,
          email: user.email
        }
      }
    });
  } catch (error) {
    console.error('Login error:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

// 注册路由
router.post('/signup', async (req, res) => {
  try {
    const { username, password, email } = req.body;

    // 检查用户是否已存在
    const existingUser = await getUserByUsername(username);
    if (existingUser) {
      return res.status(400).json({ message: '用户名已存在' });
    }

    // 加密密码
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(password, salt);

    // 创建新用户
    const newUser = await createUser({
      username,
      password: hashedPassword,
      email
    });

    // 生成 JWT token
    const token = jwt.sign(
      { userId: newUser.id, username: newUser.username },
      JWT_SECRET,
      { expiresIn: '24h' }
    );

    res.status(201).json({
      code: 200,
      message: '注册成功',
      data: {
        token,
        user: {
          id: newUser.id,
          username: newUser.username,
          email: newUser.email
        }
      }
    });
  } catch (error) {
    console.error('Registration error:', error);
    res.status(500).json({ message: '服务器错误' });
  }
});

module.exports = router;
